/*
 *
 * FileName: ConnectWatcher.java
 * Author:   wx:fdzhangc
 * Date:     2021/11/24 16:44
 * Description: //模块目的、功能描述
 * History: //修改记录
 * <author>      <time>      <version>    <desc>
 * 修改人姓名    修改时间    版本号       描述
 */
package com.zhangc.zcscm.simple;

import java.io.IOException;
import java.util.concurrent.CountDownLatch;

import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;

/**
 * 功能描述:<br>
 *
 * @author wx:fdzhangc
 * @see [相关类/方法]（可选）
 * @since [产品/模块版本] （可选）
 */
public class ConnectWatcher implements Watcher {
    private final static String ZK_HOST = "10.37.168.137:2181";
    private final static int SESSION_TIME_OUT = 3000;
    private CountDownLatch countDownLatch = new CountDownLatch(1);
    ZooKeeper zooKeeper;

    public void process(WatchedEvent watchedEvent) {
        if (watchedEvent.getState() == Event.KeeperState.SyncConnected) {
            countDownLatch.countDown();
        }
    }

    public void connect() {
        try {
            zooKeeper = new ZooKeeper(ZK_HOST, SESSION_TIME_OUT, this);
            countDownLatch.await();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public void close() {
        try {
            this.zooKeeper.close();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
